package utils

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/json"
)

type WebSocketResp struct {
	Meta interface{} `json:"meta"`
	Data interface{} `json:"data"`
}

type WebSocketPushMsg struct {
	Command string 		`json:"command"`
	Data 	interface{} `json:"data"`
}

func JSON(data interface{}, c *gin.Context) {
	res := newResApi(data)
	c.JSON(http.StatusOK, res)
}

func Error(err interface{}, c *gin.Context) {
	fmt.Println("err: ", err)
	switch err.(type) {
	case error:
		fmt.Println("原始err")
		errT := MakeError(err.(error))
		errorT(errT, c)
	case *ErrorType:
		fmt.Println("自定义err")
		errorT(err.(*ErrorType), c)
	default:
		fmt.Println("err type invalid:", err)
	}
}

func errorT(err *ErrorType, c *gin.Context) {
	res := newErrApi(err.ErrorCode, err.ErrorMsg)
	c.JSON(err.StatusCode, res)
}

func WsError(err interface{}) []byte {
	var (
		reErr 	 *ErrorType
		resp     *WebSocketResp
		jsonResp []byte
	)
	resp = new(WebSocketResp)
	switch err.(type) {
	case error:
		fmt.Println("原始err")
		reErr = MakeError(err.(error))
	case *ErrorType:
		reErr = err.(*ErrorType)
	default:
		fmt.Println("err type invalid:", err)
	}
	resp.Data = nil
	resp.Meta = reErr
	if jsonResp, err = json.Marshal(resp); err != nil {
		fmt.Printf("json Marshal err: %s", err)
	}
	return jsonResp
}

func WsJson(data interface{}) []byte {
	var (
		resp     *WebSocketResp
		jsonResp []byte
		err 	 error
	)
	resp = new(WebSocketResp)
	resp.Meta = &ErrorType{
		StatusCode: 200,
		ErrorCode:  0,
		ErrorMsg:   "success",
	}
	resp.Data = data
	if jsonResp, err = json.Marshal(resp); err != nil {
		fmt.Printf("json Marshal err: %s", err)
	}
	return jsonResp
}

//封装websocket推送信息
func WsPushMsg(command string, data interface{}) []byte {
	var (
		jsonResp []byte
		info 	 *WebSocketPushMsg
		err		 error
		resp     *WebSocketResp
	)
	info = new(WebSocketPushMsg)
	info.Command = command
	info.Data = data
	resp = new(WebSocketResp)
	resp.Meta = &ErrorType{
		StatusCode: 200,
		ErrorCode:  0,
		ErrorMsg:   "success",
	}
	resp.Data = info
	if jsonResp, err = json.Marshal(resp); err != nil {
		fmt.Printf("json Marshal err: %s", err)
	}
	return jsonResp
}
